<template>
  <div class="employees-container">
    <!-- 顶部工具栏 -->
    <PageTools>
      <!-- 具名插槽  slot= 简写 # -->
      <template #slot-left>
        <span>共{{ total }}条数据</span>
      </template>
      <template #slot-right>
        <el-button type="danger" size="medium" @click="goUploadExcel">导入excel</el-button>
        <el-button type="success" size="medium" @click="downloadExcel">导出excel</el-button>
        <el-button type="primary" size="medium" @click="showAddEmployees"
          >新增员工</el-button
        ></template
      >
    </PageTools>
    <el-card class="app-container">
      <el-table border :data="this.employeesList">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像" prop="staffPhoto">
          <template v-slot="{ row }">
            <img class="profile-photo" :src="row.staffPhoto" @error="dufImg" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="filterTag" />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry">
          <template v-slot="{ row }">
            {{ formatMD(row.timeOfEntry, 'YYYY年MM月DD日') }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280">
          <template>
            <el-button type="text" size="small">分配角色</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <EmployeesDialog
      :dialogFormVisible.sync="dialogFormVisible"
      :treeData="treeData"
      @addEmployee="addEmployee"
    ></EmployeesDialog>
  </div>
</template>

<script>
import PageTools from '@/components/PageTools'
import { getEmployees, getCompanyDepartment, addEmployee } from '@/api'
import EmployeesDialog from './cpns/employeesDialog'
import getTree from '@/utils/getTree'
import { formatMD } from '@/utils/format_date'
export default {
  name: 'employees',
  data() {
    return {
      defualtSrc: '@/assets/normalPeople.svg',
      total: 0,
      employeesList: [], //员工列表
      dialogFormVisible: false, // 是否显示弹窗
      hireType: [
        { key: 1, value: '正式' },
        { key: 2, value: '外包' },
      ], // 员工类型
      treeData: [], // 树状数组
      query: {
        page: 1, // 页码
        size: 5, // 每页数据大小
      },
    }
  },
  created() {
    this.fetchEmployees()
    this.fetchCompanyDepartment()
  },
  methods: {
    // 获取员工列表
    async fetchEmployees() {
      const res = await getEmployees(this.query.page, this.query.size)
      this.employeesList = res.data.rows
      this.total = res.data.total
      // console.log(this.employeesList)
    },
    // 获取部门列表
    async fetchCompanyDepartment() {
      const { data: res } = await getCompanyDepartment()
      // 后端返回的是 扁平化的数组 重新生成 树状数组
      this.treeData = getTree(res.depts, '')
    },
    // 添加员工
    async addEmployee(data) {
      const res = await addEmployee(data)

      if (res.success) {
        this.$message.success(res.message)
        // 提示后, 重新请求列表
        this.fetchEmployees(this.query.page, this.query.size)
      } else {
        this.$message.error(res.message)
      }
    },
    // 每页条数修改
    handleSizeChange(val) {
      this.query.pagesize = val
      console.log(this.query)
      this.fetchEmployees()
    },
    // 当前页修改
    handleCurrentChange(val) {
      this.query.page = val
      this.fetchEmployees()
    },
    // 格式化 入职方式
    filterTag(row, value, column) {
      const hireObj = this.hireType.find((item) => item.key === row.formOfEmployment) || {
        key: 0,
        value: '未知',
      }
      return hireObj.value
    },
    // 格式化入职时间  formatMD 等于utils中的format_data.js的formatMD
    formatMD,
    // 添加用户弹窗
    showAddEmployees() {
      this.dialogFormVisible = true
      console.log(1)
    },
    // 如果图片加载不出 使用默认图片
    dufImg(e) {
      const img = e.srcElement
      ;(img.src = require('@/assets/normalPeople.svg')), (img.onerror = null) //防止闪图
    },
    // 跳转到Excel上传页
    goUploadExcel() {
      this.$router.push('/uploadExcel')
    },
    // 整理数据 组成 header和data
    transData(rowData) {
      const nameMap = {
        id: '编号',
        // password: '密码', 不展示密码
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址',
      }
      // 获取到数组中的每行数据的组成形式
      const headerKeys = Object.keys(rowData[0])
      const nameMapkey = Object.keys(nameMap)
      const header = []
      const data = []
      // 过滤出需要的值 并转换中文数组
      nameMapkey.forEach((item) => {
        if (headerKeys.includes(item)) {
          // 将会按照nameMap排序输出
          header.push(nameMap[item])
        }
      })
      rowData.forEach((element) => {
        // 根据headerKey获取对应的数据 将会按照nameMap排序输出
        const arr = nameMapkey.map((item) => {
          return element[item]
        })
        data.push(arr)
      })
      return { header, data }
    },
    // 下载Excel
    async downloadExcel() {
      const res = await getEmployees(1, this.total)
      const excelObj = this.transData(res.data.rows)
      const formatDate = formatMD(new Date(), 'YYYY年MM月DD日')
      // import('@/vendor/Export2Excel').then(excel => {})  什么时候正式要使用导出功能了,插件才会被正式引入到应用里
      import('@/utils/Export2Excel').then((excel) => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 导出数据的表头	Array 必填
          data: excelObj.data, // 导出的具体数据 (一行数据 对应每个header)	Array 必填
          filename: formatDate + 'download-excel', //导出文件名	String 非必填
          autoWidth: true, // 单元格是否要自适应宽度	Boolean 非必填
          bookType: 'xlsx', //导出文件类型	String 非必填
        })
      })
    },
  },
  components: { PageTools, EmployeesDialog },
}
</script>

<style lang="less" scoped>
.profile-photo {
  width: 50%;
  background-color: var(--themeColor);
  border-radius: 10px;
}
</style>
